﻿<%@ WebHandler Language="C#" Class="Apollo.Website.Autocomplete" %>

using System;
using System.Collections;
using System.Web;
using System.Linq;
using NHibernate;
using NHibernate.Criterion;


namespace Apollo.Website
{
    public class Autocomplete : IHttpHandler, System.Web.SessionState.IRequiresSessionState
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";

            
            
            int viewId = 0;
            if (int.TryParse(context.Request["ViewId"], out viewId))
            {
                EntityView entityView = Apollo.Application.Meta<EntityView>()
                            .SingleOrDefault<EntityView>(e => e.Id == viewId);

                ICriteria crit = Application.CurrentSession.CreateCriteria(entityView.Entity.MappedClass);
                crit.Add(Expression.Like(entityView.Entity.DisplayProperty, context.Request["term"], MatchMode.Anywhere));
                crit.AddOrder(Order.Asc(entityView.Entity.DisplayProperty));
                crit.SetProjection(
                    Projections.ProjectionList()
                        .Add(Projections.Property(entityView.Entity.IdentifierProperty))
                        .Add(Projections.Property(entityView.Entity.DisplayProperty))
                );
                crit.SetResultTransformer(NHibernate.Transform.Transformers.ToList);

                IList result = crit.SetMaxResults(10).List();


                context.Response.Write("[");
                bool isFirst = true;
                
                foreach (IList row in result) {
                    if (isFirst) isFirst = false;
                    else context.Response.Write(",");

                    context.Response.Write(@"{ ""value"": """
                        + Apollo.Application.Serialize(row[0]) + @""", ""label"": """
                        + Apollo.Application.Serialize(row[1]) + @""" }");    
                }
                context.Response.Write("]");
                context.Response.End();
                
            }
            
            context.Response.Write(@"[ ]");    
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }

    }
}